package com.leyou.user.web;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.UserHolder;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("info")
public class UserInfoController {

    @Autowired
    private UserService userService;

    /**
     * 校验数据是否存在
     * @param data 数据
     * @param type 数据的类型 1.用户名  2.手机号
     * @return  是否存在
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> isExits(@PathVariable("data") String data ,@PathVariable("type") Integer type){
        return ResponseEntity.ok(userService.isExits(data,type));
    }

    /**
     * 发送短信验证码
     * @param phone 手机号码
     * @return   无
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone){
        userService.sendVerifyCode(phone);
        return ResponseEntity.noContent().build();
    }

    /**
     * 注册用户
     * @param user 用户信息
     * @param code 验证码
     * @return 无
     */
    @PostMapping
    public ResponseEntity<Void> register(@Valid User user , BindingResult result, @RequestParam("code") String code){
        if (result.hasErrors()){
            throw new LyException(400,"请求参数有误");
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户
     * @param username  用户名
     * @param password  密码
     * @return  用户信息
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username  , @RequestParam("password") String password){
        return ResponseEntity.ok(userService.queryUserByUsernameAndPassword(username,password));
    }

    @GetMapping("/me")
    public ResponseEntity<UserDetails>whoAmI(){
        return ResponseEntity.ok(UserHolder.getUser());
    }
}
